package com.example.s.network;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Looper;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

public class MyNetwork {
//    public static String BASE_URL = "http://www.daizhongdai.xyz:3004";
    public static String BASE_URL = "http://10.0.2.2:3000";
    public static MyNetwork myNetwork;
    private Context context;
    private RequestQueue requestQueue;
    private String TAG = getClass().getSimpleName();

    private MyNetwork(Context context) {
        this.context = context;
        requestQueue = Volley.newRequestQueue(context);
    }

    public static MyNetwork getInstance(Context context) {
        if (myNetwork == null) {
            synchronized (MyNetwork.class) {
                if (myNetwork == null) {
                    myNetwork = new MyNetwork(context);
                }
            }
        }
        return myNetwork;
    }


    public void get(String url, OnMyNetworkListener listener) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, BASE_URL + url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, "onResponse: " + BASE_URL + url);
                if ("S".equals(response.optString("RESULT"))) {
                    Log.d(TAG, "success: " + response);
                    listener.success(response);
                } else {
                    listener.fail(response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                new AlertDialog.Builder(context).setTitle("网络错误！").show();
                Log.e(TAG, "onErrorResponse: " + error);
                listener.fail(null);
            }
        });
        requestQueue.add(jsonObjectRequest);
    }

    public void post(String url, HashMap<String, Object> map, OnMyNetworkListener listener) {
        post(url, map, false, listener);
    }

    public void post(String url, HashMap<String, Object> map, boolean isToken, OnMyNetworkListener listener) {
        OkHttpClient builder = new OkHttpClient.Builder()
                .build();
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
        for (Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value instanceof File) {
                MediaType mediaType = MediaType.parse("image/*");
                RequestBody requestBody = RequestBody.create((File) value, mediaType);
                Log.d(TAG, "uploadImg: " + value);
                bodyBuilder.addFormDataPart(key, ((File) value).getName(), requestBody);
            }
            bodyBuilder.addFormDataPart(key, String.valueOf(value));

        }
        MultipartBody build = bodyBuilder.setType(MultipartBody.FORM).build();
        okhttp3.Request.Builder post = new okhttp3.Request.Builder()
                .url(BASE_URL + url)
                .post(build);
        if (isToken) {
            String token = context.getSharedPreferences("user", Context.MODE_PRIVATE).getString("token", "0");
            if ("0".equals(token)) {
                new AlertDialog.Builder(context).setTitle("token不存在").show();
                return;
            }
            post.addHeader("token", token);
            post.addHeader("Content-Type", "form-data");
        }
        okhttp3.Request request = post.build();

        Call call = builder.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Looper.prepare();
                new AlertDialog.Builder(context).setTitle("网络错误！").show();
                Looper.loop();
                Log.e(TAG, "网络错误 ！");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull okhttp3.Response response) throws IOException {
                try {
                    String body = response.body().string();
                    Log.d(TAG, "onResponse: " + body);
                    JSONObject jsonObject = new JSONObject(body);
                    Looper.prepare();
                    if ("S".equals(jsonObject.optString("RESULT"))) {
                        listener.success(jsonObject);
                    } else {
                        listener.fail(jsonObject);
                    }
                    Looper.loop();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e(TAG, "post 解析response错误!");
                }

            }
        });

    }


}
